﻿using Sustainalytics.Claims;
using Sustainalytics.DynamicsCRMGateway;
using Sustainalytics.DynamicsCRMGateway.Entities;
using Sustainalytics.Utils;
using System;
using System.Configuration;
using System.Linq;

namespace Sustainalytics.ClaimsProvisioningInCRM
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var accounts = ConfigurationManager.AppSettings["Accounts"];
                if (accounts == null)
                    throw new ArgumentException("No accounts specified in the config file!");

                var connectionStringSetting = ConfigurationManager.ConnectionStrings["SustainalyticsCRM"];
                if(connectionStringSetting==null)
                    throw new ArgumentException("No CRM connection string specified in the config file!");

                var crmConnectionString = connectionStringSetting.ConnectionString;
                var crmServiceContextFactory = new CrmServiceContextFactory();
                var crmServiceContext = crmServiceContextFactory.GetCrmServiceContext(crmConnectionString);
                var claimsProvisioning = new ClaimsProvisioning(
                    new OperationClaimsRetriever(),
                    accounts.Split(';').Select(acc => 
                        {
                            var accParts = acc.Split(',');
                            if (accParts.Length != 2)
                                throw new Exception("Invalid accounts list!");

                            return new Sustainalytics.Entities.Account() { Name = accParts[0].Trim(), Id = new Guid(accParts[1].Trim()) };
                        }).ToList(),
                    new CrmRepository<Sustainalytics.DynamicsCRMGateway.Entities.Account>(crmServiceContext),
                    new CrmRepository<AccountFeature>(crmServiceContext),
                    new CrmRepository<Feature>(crmServiceContext),
                    new CrmRepository<Claim>(crmServiceContext),
                    crmServiceContext);
                
                claimsProvisioning.ProcessClaims();
            }
            catch(Exception ex)
            {
                CommonEventSource.Log.Exception(ex);
            }
        }
    }
}
